#!/usr/bin/python 

"""
Copyright 2008 Israel Garcia

This file is part of Audlib.
Audlib is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.

Audlib is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Audlib.  If not, see <http://www.gnu.org/licenses/>.
"""

import os, os.path, re, sqlite3, sys

DB_PATH = '/home/israel/.local/var/audlib/audacious.lib'
MUSIC_FIELDS_HEADERS = [ 'track_no', 'title', 'artist',  'album', 'duration', 'comment', 'location']
MUSIC_FIELDS = {'location' : 0, 'artist' : 1, 'album' : 2, 'title' : 3, 'duration' : 4, 'track_no' : 5, 'comment' : 6}
MUSIC_FIELDS_TYPES = {'uri' : str, 'artist' : str, 'album' : str, 'title' : str, 'duration' : str, 'track_no' : int, 'comment' : str}

try:
    db = sqlite3.connect(DB_PATH)
except:
    datadir = os.path.dirname(DB_PATH)
    if not os.path.exists(datadir):
        os.makedirs(datadir)
        db = sqlite3.connect(DB_PATH)

c = db.cursor()

def normalize(w):
    try:
        w = w.lower()
        words = w.split()
        return ' '.join(words)
    except:
        return w

def remove_space(w):
    try:
        words = w.split()
        return ' '.join(words)
    except:
        return w

def create_table():
    c.execute('create table music (uri text, artist text, album text, title text, duration text, track_no int, comment text)')

def get_table():
    c.execute('select * from music')
    return c

def insert_info(array):
    for t in array:
        t2 = [remove_space(w) for w in t]
        t3 = tuple(t2)
        c.execute('insert into music values (?, ?, ?, ?, ?, ?, ?)', t3)
        db.commit()

#def retrieve_info(w):
#    c.execute('select * from music where uri = ? or artist = ? or album = ? or title = ? or duration = ? or comment = ?', (w, w, w, w, w, w,))
#    return c

def retrieve_info(w):
    word = remove_space(w)
    res = []
    c.execute('select * from music')
    for row in c:
        for item in row:
            if item.count(word):
                res.append(row)
                break
    return res
